import React, { useRef, useState, useEffect } from 'react'
import { Button, Select, Input, message, Typography, Row, Col, Modal, Upload } from 'antd';
import { useNavigate } from 'react-router-dom'
import './index.css'
import axios from 'axios';
const { Option } = Select;
const { Title } = Typography;

export default function Index() {
    const [formLeft, setFormLeft] = useState("30%")
    const [formState, setFormState] = useState("login")
    const [captchImg, setCaptchImg] = useState('http://localhost:8080/kaptcha')
    const [userType, setUserType] = useState("user")
    const [registerAble, setRegisterAble] = useState(true) //用户注册按钮是否有效
    const [registerAble2, setRegisterAble2] = useState(true) //机构注册按钮是否有效
    const [file, setFile] = useState();
    const [emailLoading, setEmailLoading] = useState(false)
    const emailOrPhone = useRef();//登入输入的手机或者邮箱
    const loginPwd = useRef();
    const captchaRef = useRef()//登入输入的验证码
    const registerEmail = useRef();
    const registerPwd = useRef();
    const confirmPwd = useRef();
    const emailCode = useRef();

    const orgNameRef = useRef();
    const orgEmailRef = useRef();
    const orgPwdRef = useRef();
    const orgPwdCheck = useRef();
    const orgemailCode = useRef()

    const [disabled, setDisabled] = useState(true);  //注册获取邮箱验证码按钮是否可用
    const [disabled2, setDisabled2] = useState(true);  //注册获取邮箱验证码按钮是否可用

    const navigate = useNavigate();

    const newPwd = useRef()
    const newPwd2 = useRef()
    const checkNewPwd = useRef();
    const checkNewPwd2 = useRef();
    const forgetEmailUser = useRef();
    const forgetEmailOrg = useRef();
    const [forgetLoading, setForgetLoading] = useState(false)
    const [forgetLoading2, setForgetLoading2] = useState(false)
    const forgetEmailCode = useRef()
    const forgetEmailCode2 = useRef()
    const [userForgetVis, setuserForgetVis] = useState(false)
    const [orgForgetVis, setorgForgetVis] = useState(false)
    useEffect(() => {

    }, [])
    const props = {
        onRemove: file => {
            setFile("")
        },
        beforeUpload: file => {
            setFile(file)
            return false;
        },
        file,
    };
    const gotoRegister = () => {
        setFormLeft("50%")
        setFormState("register")
        setUserType("user")
    }
    const gotoLogin = () => {
        setFormLeft("30%")
        setFormState("login")
        setUserType("user")
    }
    const refreshCaptch = () => {
        setCaptchImg('http://localhost:8080/kaptcha?' + Math.random());   //再次请求 带一个随机数参数 达到更新
    }
    const handleLogin = () => {
        if (userType == "user") {
            const loginInfo = {}
            loginInfo.emailOrPhone = emailOrPhone.current.state.value
            loginInfo.password = loginPwd.current.state.value
            loginInfo.captcha = captchaRef.current.state.value
            if (loginInfo.emailOrPhone == '' || loginInfo.emailOrPhone == null || loginInfo.password == "" || loginInfo.password == null || loginInfo.captcha == "" || loginInfo.captcha == null) {
                message.error("请输入登入信息!", 1)
            } else {
                axios.post("http://localhost:8080/login", loginInfo).then(resp => {
                    localStorage.clear();
                    console.log("返回的信息:", resp);
                    switch (resp.data.state) {
                        case '0':
                            //登入成功清除之前的登入用户信息
                            const loginUser = resp.data.loginUser; //这个是json格式的字符串 如果要变成js对象用要用JSON.parse()方法
                            // if(resp.data.remember){ //保持登入 数据存到localStorage
                            localStorage.setItem("loginUser", loginUser);
                            console.log("本地localStorage信息:", JSON.parse(localStorage.getItem("loginUser")));
                            // }
                            message.success(resp.data.message, 1)
                            if (loginUser.role == 1) {
                                setTimeout(() => {
                                    navigate('/userMenu/*')
                                }, 0);
                            } else {
                                setTimeout(() => {
                                    navigate('/adminMenu/*')
                                }, 0);
                            }

                            break;
                        case '1':
                            message.error(resp.data.message, 1);
                            userPwdRef.current.state.value = '';
                            userPwdRef.current.state.focused = true;
                            break;
                        case '2':
                            message.error(resp.data.message, 1)
                            console.log(captchaRef);
                            captchaRef.current.focus();
                            break;
                    }
                })
                refreshCaptch()
            }
            console.log(loginInfo);
        } else {
            //机构登入
            const orgloginInfo = {}
            orgloginInfo.email = emailOrPhone.current.state.value
            orgloginInfo.password = loginPwd.current.state.value
            orgloginInfo.captcha = captchaRef.current.state.value
            console.log("机构登入信息:", orgloginInfo);
            if (orgloginInfo.email == '' || orgloginInfo.email == null || orgloginInfo.password == "" || orgloginInfo.password == null || orgloginInfo.captcha == "" || orgloginInfo.captcha == null) {
                message.error("请输入登入信息!", 1)
            } else {
                axios.post("http://localhost:8080/orgLogin", orgloginInfo).then(resp => {
                    console.log(resp);
                    if (resp.data.state == "0") {
                        localStorage.clear()
                        const loginOrg = resp.data.loginOrg; //这个是json格式的字符串 如果要变成js对象用要用JSON.parse()方法
                        localStorage.setItem("loginOrg", loginOrg);
                        console.log("本地localStorage信息:", JSON.parse(localStorage.getItem("loginOrg")));
                        message.success(resp.data.message, 1)
                        setTimeout(() => {
                            navigate('/orgMenu/*')
                        }, 100);
                    } else {
                        message.error(resp.data.message, 3)
                    }
                })
            }
            refreshCaptch()
        }


    }
    const handleRegister = () => {
        message.destroy()
        const registerInfo = {}
        registerInfo.email = registerEmail.current.state.value;
        registerInfo.emailCode = emailCode.current.state.value;
        const pwdReg = /^[a-zA-Z0-9]{6,18}$/;
        if (!pwdReg.test(registerPwd.current.state.value)) {
            message.error("密码为6-18位包含数字字母的组合!")
            return
        }
        if (confirmPwd.current.state.value === registerPwd.current.state.value) {
            registerInfo.password = registerPwd.current.state.value
        } else {
            message.error("两次密码不一致!")
            return
        }

        console.log(registerInfo);
        if (registerInfo.email == '' || registerInfo.email == null || registerInfo.password == "" || registerInfo.password == null || registerInfo.emailCode == "" || registerInfo.emailCode == null) {
            message.error("请填写注册信息!", 1)
        } else {
            axios.post("http://localhost:8080/register", registerInfo)
                .then((resp) => {
                    if (resp.data.state == '0') {
                        message.success(resp.data.message, 1); //注册成功
                        setTimeout(() => {
                            window.location.reload();
                        }, 300);
                    } else {
                        message.error(resp.data.message, 1)
                    }
                })
                .catch(err => { console.log(err); })
        }
    }
    const registeremailChange = () => {
        const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
        if (reg.test(registerEmail.current.state.value)) {
            setDisabled(false)
        } else {
            setDisabled(true)
        }
    }
    const orgemailChange = () => {
        const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
        if (reg.test(orgEmailRef.current.state.value)) {
            setDisabled2(false)
        } else {
            setDisabled2(true)
        }
    }
    const sendEmailCode = () => {
        const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
        if (reg.test(registerEmail.current.state.value)) {
        } else {
            message.error("邮箱格式错误!", 1)
            return
        }
        setDisabled(true)
        setEmailLoading(true)
        axios.post("http://localhost:8080/getEmailCode", { userEmail: registerEmail.current.state.value })
            .then((resp) => {
                setDisabled(false)
                setEmailLoading(false)
                console.log(resp);
                if (resp.data.state == "0") {
                    message.success(resp.data.message, 1)
                    setRegisterAble(false)  //只有发送了邮箱验证码才能点击注册
                } else {
                    message.error(resp.data.message, 1)
                }
            })
            .catch(err => {
                console.log(err);
                message.error("网络异常,请售后再试!", 1)
            })
    }

    const sendEmailCodeOrg = () => {
        const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
        if (reg.test(orgEmailRef.current.state.value)) {
        } else {
            message.error("邮箱格式错误!", 1)
            return
        }
        setDisabled2(true)

        axios.post("http://localhost:8080/getEmailCodeOrg", { orgEmail: orgEmailRef.current.state.value })
            .then((resp) => {
                console.log(resp);
                setDisabled2(false)
                if (resp.data.state == "0") {
                    message.success(resp.data.message, 1)
                    setRegisterAble2(false)  //只有发送了邮箱验证码才能点击注册
                } else {
                    message.error(resp.data.message, 1)
                }
            })
            .catch(err => {
                console.log(err);
                message.error("网络异常,请售后再试!", 1)
            })

    }
    const userTypeChange = (value) => {
        setUserType(value)
    }
    const photoupdate = (info) => {
        if (info.file.status !== 'uploading') {
            console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
            message.success(`${info.file.name} file uploaded successfully`);
        } else if (info.file.status === 'error') {
            message.error(`${info.file.name} file upload failed.`);
        }

    }
    const beforeUpload = (file) => {
        console.log(file.size);
        if (file.size > (2097152)) {
            console.log("图片超过2M");
            message.error(`图片不得超过2M`);
            return Upload.LIST_IGNORE;
        } else {
            return true;
        }
    }
    const orgRegister = () => {
        console.log("机构注册");
        const pwd = orgPwdRef.current.state.value;
        const checkPwd = orgPwdCheck.current.state.value;
        const pwdReg = /^[a-zA-Z0-9]{6,18}$/;
        if (!pwdReg.test(pwd)) {
            message.error("密码为6-18位包含数字字母的组合!")
            return
        }
        let orgRegisterInfo = { orgname: orgNameRef.current.state.value, orgemail: orgEmailRef.current.state.value, emailcode: orgemailCode.current.state.value };

        if (pwd == checkPwd) {
            orgRegisterInfo.orgpassword = pwd;
        } else {
            orgRegisterInfo.orgpassword = "";
            message.error("两次密码不一致!", 1);
            return
        }
        if (file == "" || file == null) {
            message.error("请上传证明图片!", 1);
            return
        }
        // 申请机构 先把申请信息保存 再保存申请的证明图片
        if (orgRegisterInfo.orgemail != null && orgRegisterInfo.orgemail != "" && orgRegisterInfo.orgpassword != null && orgRegisterInfo.orgpassword != "" && orgRegisterInfo.emailcode != null && orgRegisterInfo.emailcode != "") {
            let params = new FormData()
            params.append("file", file)
            params.append("orgemail", orgRegisterInfo.orgemail)
            params.append("orgpassword", orgRegisterInfo.orgpassword)
            params.append("orgname", orgRegisterInfo.orgname)
            params.append("orgemailCode", orgRegisterInfo.emailcode)
            axios.post("http://localhost:8080/orgRegisterApply", params, { headers: { 'Content-Type': 'multipart/form-data' } }).then(resp => {
                console.log(resp);
                if (resp.data.state === "0") {
                    message.success(resp.data.message, 10)
                    setRegisterAble2(true);
                    setDisabled2(true)
                } else {
                    message.error(resp.data.message)
                }
            })



        }
    }
    const getforgetEmailUser = () => {

        if (forgetEmailUser.current.state.value == null || forgetEmailUser.current.state.value == "") {
            message.error("请输入邮箱!")
            return
        }
        const emailReg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
        if (!emailReg.test(forgetEmailUser.current.state.value)) {
            message.error("邮箱格式错误!")
            return
        } else {
            setForgetLoading(true)
            setTimeout(() => {
                axios.post("http://localhost:8080/forgetEmailCodeUser?email=" + forgetEmailUser.current.state.value).then(resp => {
                    setForgetLoading(false)
                    if (resp.data.state == "0") {
                        message.success(resp.data.message, 1)
                    } else {
                        message.error(resp.data.message, 1)
                    }
                })
            }, 1);


        }
    }
    const getforgetEmailOrg = () => {
        if (forgetEmailOrg.current.state.value == null || forgetEmailOrg.current.state.value == "") {
            message.error("请输入邮箱!")
            return
        }
        const emailReg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
        if (!emailReg.test(forgetEmailOrg.current.state.value)) {
            message.error("邮箱格式错误!")
            return
        } else {
            setForgetLoading2(true);
            axios.post("http://localhost:8080/forgetEmailCodeOrg?email=" + forgetEmailOrg.current.state.value).then(resp => {
                setForgetLoading2(false)
                if (resp.data.state == "0") {
                    message.success(resp.data.message, 1)
                } else {
                    message.error(resp.data.message, 1)
                }
            })

        }
    }



    const forgetPwd = () => {
        const pwdReg = /^[a-zA-Z0-9]{6,18}$/;
        if (forgetEmailUser.current.state.value == "" || forgetEmailUser.current.state.value == null) {
            message.error("请输入邮箱!")
            return
        }
        if (newPwd.current.state.value == "" || newPwd.current.state.value == null) {
            message.error("请输入密码!")
            return
        }
        if (!pwdReg.test(newPwd.current.state.value)) {
            message.error("密码为6-18位包含数字字母的组合!")
            return
        }
        if (newPwd.current.state.value != checkNewPwd.current.state.value) {
            message.error("两次密码不一致!")
            return
        }
        let params = { email: forgetEmailUser.current.state.value, code: forgetEmailCode.current.state.value, pwd: newPwd.current.state.value }

        axios.post("http://localhost:8080/forgetPwd", params).then(resp => {

            if (resp.data.state == "0") {
                message.success(resp.data.message)
                window.location.reload();
            } else {
                message.error(resp.data.message)
            }
        })
    }
    const forgetPwd2 = () => {
        const pwdReg = /^[a-zA-Z0-9]{6,18}$/;
        if (forgetEmailOrg.current.state.value == "" || forgetEmailOrg.current.state.value == null) {
            message.error("请输入邮箱!")
            return
        }
        if (newPwd2.current.state.value == "" || newPwd2.current.state.value == null) {
            message.error("请输入密码!")
            return
        }
        if (!pwdReg.test(newPwd2.current.state.value)) {
            message.error("密码为6-18位包含数字字母的组合!")
            return
        }
        if (newPwd2.current.state.value != checkNewPwd2.current.state.value) {
            message.error("两次密码不一致!")
            return
        }
        let params = { email: forgetEmailOrg.current.state.value, code: forgetEmailCode2.current.state.value, pwd: newPwd2.current.state.value }

        axios.post("http://localhost:8080/forgetPwdOrg", params).then(resp => {

            if (resp.data.state == "0") {
                message.success(resp.data.message)
                window.location.reload();
            } else {
                message.error(resp.data.message)
            }
        })



    }


    return (
        <Row style={{ height: '100vh', display: 'flex', justifyContent: 'center', alignItems: 'center', paddingLeft: '20%' }} className="logregisterbg">
            <div style={{ width: '40%', height: userType == "user" ? "50%" : "60%", display: 'flex', justifyContent: 'space-between' }} className="logregisterbg2">
                <div style={{ display: 'flex', justifyContent: "center", alignItems: 'center', flexDirection: 'column', width: '50%' }}>
                    <Title level={2}>进入系统</Title>
                    <Button style={{ height: 40 }} onClick={gotoLogin} >去登入</Button>
                </div>

                <div style={{ display: 'flex', justifyContent: "center", alignItems: 'center', flexDirection: 'column', width: '50%' }}>
                    <Title level={2}>加入我们</Title>
                    <Button style={{ height: 40 }} onClick={gotoRegister}>去注册</Button>
                </div>

                <div className="myform" style={{ left: formLeft, height: userType == "user" ? "50%" : "60%" }}>
                    {
                        formState === "login" ?
                            <div style={{ padding: 30, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
                                <Input placeholder={userType == "user" ? "邮箱号/手机号" : "机构邮箱"} ref={emailOrPhone} />
                                <Input type="password" placeholder="密码" style={{ marginTop: 20 }} ref={loginPwd} />
                                <div style={{ width: '100%', display: 'flex', justifyContent: 'space-between', marginTop: 20, alignItems: 'center' }}>
                                    <Input style={{ width: '40%' }} placeholder="验证码" ref={captchaRef} />
                                    <img src={captchImg} alt="" style={{ cursor: 'pointer' }} onClick={refreshCaptch} />
                                </div>
                                <div style={{ width: '100%', display: 'flex', marginTop: 20, justifyContent: 'space-between', alignItems: 'center' }}>
                                    <Button type="primary" style={{ display: 'block' }} onClick={handleLogin}>登入</Button>
                                    <Select defaultValue="user" style={{ width: 120 }} onChange={userTypeChange}>
                                        <Option value="user">用户</Option>
                                        <Option value="org">机构</Option>
                                    </Select>
                                </div>
                                {
                                    userType === "user" ?
                                        <div style={{ width: '100%', marginTop: 20, }}>
                                            <a onClick={() => { setuserForgetVis(true) }}>忘记密码?</a>
                                        </div> : <div style={{ width: '100%', marginTop: 20, }}>
                                            <a onClick={() => { setorgForgetVis(true) }}>忘记密码?</a>
                                        </div>
                                }

                            </div> :
                            <div style={{ padding: 30, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
                                {
                                    userType === "user" ?
                                        <>
                                            <Input placeholder="邮箱号" ref={registerEmail} onChange={registeremailChange} />
                                            <Input placeholder="密码" type="password" style={{ margin: 20 }} ref={registerPwd} />
                                            <Input placeholder="确认密码" type="password" style={{ marginBottom: 20 }} ref={confirmPwd} />

                                            <div style={{ width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                                <Input style={{ width: '40%' }} placeholder="验证码" ref={emailCode} />
                                                <Button style={{ display: 'block' }} disabled={disabled} onClick={sendEmailCode} loading={emailLoading}>获取</Button>
                                            </div>
                                            <div style={{ width: '100%', display: 'flex', marginTop: 20, justifyContent: 'space-between', alignItems: 'center' }}>
                                                <Button type="primary" style={{ display: 'block' }} onClick={handleRegister} disabled={registerAble}>注册</Button>
                                                <Select defaultValue={userType} style={{ width: 120 }} onChange={userTypeChange}>
                                                    <Option value="user">用户</Option>
                                                    <Option value="org">机构</Option>
                                                </Select>
                                            </div>
                                        </> :
                                        <>
                                            <Input placeholder="邮箱号" ref={orgEmailRef} onChange={orgemailChange} />
                                            <Input placeholder="密码" type="password" style={{ margin: 20 }} ref={orgPwdRef} />
                                            <Input placeholder="确认密码" type="password" style={{ marginBottom: 20 }} ref={orgPwdCheck} />

                                            <div style={{ width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                                <Input style={{ width: '40%' }} placeholder="验证码" ref={orgemailCode} />
                                                <Button style={{ display: 'block' }} disabled={disabled2} onClick={sendEmailCodeOrg}>获取</Button>
                                            </div>
                                            <Input placeholder="机构名称" style={{ marginTop: '10%' }} ref={orgNameRef} />

                                            <div style={{ width: '100%', marginTop: 20 }}>
                                                <Upload maxCount={1} {...props} onChange={photoupdate} beforeUpload={beforeUpload}>
                                                    <Button style={{ width: '100%' }}>上传证明材料</Button>
                                                </Upload>
                                            </div>
                                            <div style={{ width: '100%', display: 'flex', marginTop: 20, justifyContent: 'space-between', alignItems: 'center' }}>
                                                <Button type="primary" style={{ display: 'block' }} onClick={orgRegister} disabled={registerAble2}>注册</Button>
                                                <Select defaultValue={userType} style={{ width: 120 }} onChange={userTypeChange} >
                                                    <Option value="user">用户</Option>
                                                    <Option value="org">机构</Option>
                                                </Select>

                                            </div>

                                        </>
                                }

                            </div>

                    }
                </div>
            </div>
            <Modal
                title="修改密码"
                visible={userForgetVis}
                onOk={forgetPwd}
                onCancel={() => { setuserForgetVis(false) }}
                width={"25%"}
            >
                <div style={{ padding: 30, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
                    <Input placeholder="注册时的邮箱号" ref={forgetEmailUser} />
                    <Input placeholder="请输入新密码" type="password" style={{ margin: 20 }} ref={newPwd} />
                    <Input placeholder="确认密码" type="password" style={{ marginBottom: 20 }} ref={checkNewPwd} />

                    <div style={{ width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <Input style={{ width: '40%' }} placeholder="验证码" ref={forgetEmailCode} />
                        <Button style={{ display: 'block' }} onClick={getforgetEmailUser} loading={forgetLoading}>获取</Button>
                    </div>
                </div>
            </Modal>

            <Modal
                title="修改密码"
                visible={orgForgetVis}
                onOk={forgetPwd2}
                onCancel={() => { setorgForgetVis(false) }}
                width={"25%"}
            >
                <div style={{ padding: 30, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
                    <Input placeholder="注册时的邮箱号" ref={forgetEmailOrg} />
                    <Input placeholder="请输入新密码" type="password" style={{ margin: 20 }} ref={newPwd2} />
                    <Input placeholder="确认密码" type="password" style={{ marginBottom: 20 }} ref={checkNewPwd2} />

                    <div style={{ width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <Input style={{ width: '40%' }} placeholder="验证码" ref={forgetEmailCode2} />
                        <Button style={{ display: 'block' }} onClick={getforgetEmailOrg} loading={forgetLoading2}>获取</Button>
                    </div>
                </div>
            </Modal>
        </Row>
    )
}